package com.yami.shop.api.controller;

import com.yami.shop.api.config.DateUtil;
import com.yami.shop.api.config.HttpClient;
import com.yami.shop.api.config.ParamBuilder;
import com.yami.shop.api.config.SignHelper;
import com.yami.shop.bean.enums.OrderType;
import com.yami.shop.bean.meituan.*;
import com.yami.shop.bean.model.*;
import com.yami.shop.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class CreateOrderByShopController {


    // TEST_DELIVERY_ID，配送唯一标识，实际实现时需要替换为自己的delivery_id
    private static Long TEST_DELIVERY_ID = Long.valueOf(DateUtil.unixTime());

    // TEST_ORDER_ID 订单号，实际实现时需要替换为自己的订单id
    private static String TEST_ORDER_ID = String.valueOf(DateUtil.unixTime());

    @Autowired
    private SkuService skuService;

    @Autowired
    private UserAddrOrderService userAddrOrderService;

    @Autowired
    private UserAddrService userAddrService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private OrderService orderService;

    @PostMapping("/createOrder")
    public void testCreateOrderByShop() throws Exception {
        String appkey = OpenApiConfig.TEST_APP_KEY;
        String secret = OpenApiConfig.TEST_SECRET;

        CreateOrderByShopRequest request = buildMockRequest(appkey);

        Map<String, String> params = ParamBuilder.convertToMap(request);
        String sign = SignHelper.generateSign(params, secret);

        params.put("sign", sign);

        try {
            String res = HttpClient.post(RequestConstant.ORDER_CREATE_BY_SHOP, params);
            System.out.println("结果为"+res);
        } catch (Exception e) {
            throw e;
        }
    }

    private CreateOrderByShopRequest buildMockRequest(String appkey) {
        CreateOrderByShopRequest request = new CreateOrderByShopRequest();
        request.setAppkey(appkey);
        request.setTimestamp(DateUtil.unixTime());
        request.setVersion("1.0");

        // 设置订单号及配送服务标识
        request.setDeliveryId(TEST_DELIVERY_ID);
        request.setOrderId(TEST_ORDER_ID);

        // 设置订单类型为即时单
        request.setOrderType(OrderType.NORMAL);

        /**
         * 设置配送服务编码
         *
         * 飞速达:4002
         * 快速达:4011
         * 及时达:4012
         * 集中送:4013
         */
        request.setDeliveryServiceCode(4011);

        // 设置测试门店 id，测试门店的坐标地址为 97235456,31065079（高德坐标），配送范围3km
        request.setShopId("test_0001");

        // 设置取货人信息，请根据测试门店地址 在测试发单时合理设置送货地址
        request.setReceiverName("测试收货人");
        request.setReceiverAddress("测试收货人地址");
        request.setReceiverPhone("18523657373");
        // 收件人坐标
        request.setReceiverLng(97235458);
        request.setReceiverLat(31065074);
        // 收件人坐标类型
        request.setCoordinateType(0);

        // 设置预计送达时间为1小时以后
        request.setExpectedDeliveryTime(DateUtil.unixTime() + 3600L);

        // 设置门店流水号，门店流水号为一天中单个门店的订单序号，方便骑手线下到门店取货
        request.setPoiSeq("1");

        // 设置商品重量，单位为kg
        request.setGoodsWeight(new BigDecimal(2.5));

        // 设置商品详情
        OpenApiGoods openApiGoods = new OpenApiGoods();

        OpenApiGood openApiGood1 = new OpenApiGood();
        // 商品数量
        openApiGood1.setGoodCount(1);
        // 商品名称
        openApiGood1.setGoodName("蛋黄酥");
        // 商品单价
        openApiGood1.setGoodPrice(new BigDecimal("20.9"));
        // 商品数量单位
        openApiGood1.setGoodUnit("盒");

        OpenApiGood openApiGood2 = new OpenApiGood();
        // 商品数量
        openApiGood2.setGoodCount(1);
        // 商品名称
        openApiGood2.setGoodName("雪花酥");
        // 商品单价
        openApiGood2.setGoodPrice(new BigDecimal("30.5"));
        // 商品数量单位
        openApiGood2.setGoodUnit("盒");

        openApiGoods.setGoods(Arrays.asList(openApiGood1, openApiGood2));

        request.setGoodsDetail(openApiGoods);

        // 设置备注信息
        request.setNote("小哥麻烦快一点！");
        return request;
    }


    @PostMapping("/testPushOrder")
    public void testPushOrder(String orderNumber) throws Exception {
        String appkey = OpenApiConfig.FORMAL_APP_KEY;
        String secret = OpenApiConfig.FORMAL_SECRET;
        Order order = orderService.getOrderByOrderNumber(orderNumber);
        CreateOrderByShopRequest request = buildOrderRequest(appkey,order);

        Map<String, String> params = ParamBuilder.convertToMap(request);
        String sign = SignHelper.generateSign(params, secret);

        params.put("sign", sign);

        try {
            String res = HttpClient.post(RequestConstant.ORDER_CREATE_BY_SHOP, params);
            System.out.println("结果为"+res);
        } catch (Exception e) {
            throw e;
        }
    }

    private CreateOrderByShopRequest buildOrderRequest(String appkey,Order order) {
        CreateOrderByShopRequest request = new CreateOrderByShopRequest();
        request.setAppkey(appkey);
        request.setTimestamp(com.yami.shop.common.util.DateUtil.unixTime());
        request.setVersion("1.0");

        // 设置订单号及配送服务标识
        request.setDeliveryId(Long.valueOf(order.getOrderNumber()));
        request.setOrderId(order.getOrderNumber());

        // 设置订单类型为即时单
        request.setOrderType(OrderType.NORMAL);

        /**
         * 设置配送服务编码
         *
         * 飞速达:4002
         * 快速达:4011
         * 及时达:4012
         * 集中送:4013
         */
        request.setDeliveryServiceCode(4011);

        // 设置测试门店 id，测试门店的坐标地址为 97235456,31065079（高德坐标），配送范围3km
        request.setShopId(String.valueOf(order.getShopId()));

        double latResult=0.0;
        double lngResult = 0.0;
        StringBuffer stringBuffer =null;
        Long addorderId = order.getAddrOrderId();
        UserAddrOrder userAddrOrder = userAddrOrderService.getById(addorderId);
        if(userAddrOrder!=null){
            Long AddrId = userAddrOrder.getAddrId();
            UserAddr userAddr = userAddrService.getById(AddrId);
            if(userAddr!=null) {
                stringBuffer = new StringBuffer(userAddr.getProvince());
                stringBuffer.append(userAddr.getCity()).append(userAddr.getArea()).append(userAddr.getStreet()).append(userAddr.getAddr());
                //收件人经度（高德坐标），高德坐标 *（ 10 的六次方），如 116398419
                double cf = Math.pow(10,6);
                if(userAddr.getLat()!=null) {
                    double lat = Double.valueOf(userAddr.getLat());
                    latResult = lat*cf;
                    double lng = Double.valueOf(userAddr.getLng());
                    lngResult = lng*cf;
                }
                request.setReceiverLng(Integer.valueOf(new Double(latResult).intValue()));
                //收件人纬度（高德坐标），高德坐标 *（ 10 的六次方），如 39985005
                request.setReceiverLat(Integer.valueOf(new Double(lngResult).intValue()));
                // 设置取货人信息，请根据测试门店地址 在测试发单时合理设置送货地址
                request.setReceiverName(userAddr.getReceiver());
                request.setReceiverAddress(stringBuffer.toString());
                request.setReceiverPhone(userAddr.getMobile());
            }
        }


        // 收件人坐标类型
        request.setCoordinateType(0);

        // 设置预计送达时间为1小时以后
        request.setExpectedDeliveryTime(com.yami.shop.common.util.DateUtil.unixTime() + 3600L);

        // 设置门店流水号，门店流水号为一天中单个门店的订单序号，方便骑手线下到门店取货
        request.setPoiSeq(String.valueOf(order.getPoiSeq()));

        // 设置商品详情
        OpenApiGoods openApiGoods = new OpenApiGoods();

        //查找该订单的子订单
        List<OrderItem> itemList = orderItemService.getOrderItemsByOrderNumber(order.getOrderNumber());
        BigDecimal bigDecimal = new BigDecimal("0");
        if(itemList.size()>0){
            List<OpenApiGood> openApiGoodList = new ArrayList<OpenApiGood>();
            for(OrderItem orderItem:itemList){
                OpenApiGood openApiGood = new OpenApiGood();
                // 商品数量
                openApiGood.setGoodCount(orderItem.getProdCount());
                // 商品名称
                openApiGood.setGoodName(orderItem.getProdName());
                // 商品单价
                openApiGood.setGoodPrice(new BigDecimal(orderItem.getPrice()));
                // 商品数量单位
                //openApiGood1.setGoodUnit("盒");

                //获取skuId
                Long skuId = orderItem.getSkuId();
                Sku sku = skuService.getById(skuId);
                Double weight = sku.getWeight();
                int productCount = orderItem.getProdCount();
                BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(weight));
                if(weight!=null) {
                    bigDecimal1 = bigDecimal1.multiply(new BigDecimal(String.valueOf(productCount))).divide(new BigDecimal(1000));
                }
                bigDecimal = bigDecimal.add(bigDecimal1);
                openApiGoodList.add(openApiGood);
                openApiGoods.setGoods(openApiGoodList);
            }
            request.setGoodsDetail(openApiGoods);
            // 设置商品重量，单位为kg
            request.setGoodsWeight(bigDecimal);

        }
        // 设置备注信息
        request.setNote(order.getRemarks());
        return request;
    }





}
